package com.wangshidai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangshidai.entity.SysRolePermission;
import com.wangshidai.enums.RolePermissionEnum;
import com.wangshidai.service.SysRolePermissionService;
import com.wangshidai.mapper.SysRolePermissionMapper;
import com.wangshidai.util.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 *
 */
@Slf4j
@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements SysRolePermissionService{
    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;
    @Override
    public List<Long> queryPermissionId(long roleId) {
        List<Long> PermissionIds = sysRolePermissionMapper.queryPermissionId(roleId);
        log.info("角色：{}，权限：{}",roleId,PermissionIds);
        return PermissionIds;
    }

    @Override
    public boolean alterRolePermission(long roleId, Set<Long> permissionIds) throws BusinessException {
        QueryWrapper<SysRolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq(RolePermissionEnum.ROLE_ID, roleId);
        sysRolePermissionMapper.delete(wrapper);
        log.info("权限删除成功");
        if (permissionIds == null || permissionIds.isEmpty()) {
            return true;
        }
        long count = 0;
        SysRolePermission rolePermission ;
        for (Long permissionId : permissionIds) {
            rolePermission = new SysRolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            count+= sysRolePermissionMapper.insert(rolePermission);
        }
        if(count!=permissionIds.size()){
            throw new BusinessException("权限分配异常");
        }
        log.info("角色：{}，成功分配：{}个权限",roleId,count);
        return true;
    }

}




